package com.example.homescreen.dao;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {
	public static final int VERSION = 1;
	public SQLiteDatabase myDatabase;
	public static final String TAG = "DBHelper";
	public static final String DB_NAME = "FoodDB.db";
	public Context myContext;

	public DBHelper(Context context) {
		this(context, DB_NAME, null, VERSION);
	}

	public DBHelper(Context context, String name,
			SQLiteDatabase.CursorFactory factory, int version) {

		super(context, name, factory, version);
		myContext = context;
	}

	public void openDatabase() {
		importDatabase();
		Log.i(TAG, "open database");
	}

	public void closeDatabase() {
		myDatabase.close();
		Log.i(TAG, "close database");
	}

	public void importDatabase() {
		File f = myContext.getDatabasePath(DB_NAME);
		if (!f.exists()) {
			try {
				f.getParentFile().mkdirs();
				InputStream is = myContext.getAssets().open(DB_NAME);
				int size = is.available();
				byte[] buffer = new byte[size+1];
				is.read(buffer);
				is.close();

				FileOutputStream fos = new FileOutputStream(f);
				fos.write(buffer);
				fos.flush();
				fos.close();
			} catch (Exception e) {
				Log.e("File Error", e.getMessage());
			}
		}
		if (myDatabase == null || !myDatabase.isOpen()) {
			myDatabase = SQLiteDatabase.openDatabase(f.getAbsolutePath(), null,
					SQLiteDatabase.OPEN_READONLY);
			Log.i("Path2", f.getAbsolutePath());
		}
	}

	public SQLiteDatabase getDatabase() {
		return myDatabase;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}
}
